package cn.ffcs.uec.staffAndOutStaff.component;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.web.servlet.Servlets;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;

import cn.ffcs.uec.staffAndOutStaff.component.bean.OutStaffSalaryDetailListboxExtBean;
import cn.ffcs.uec.staffAndOutStaff.manager.OutStaffImportListManager;
import cn.ffcs.uec.staffAndOutStaff.vo.OutStaffSalaryDetail;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ExportExcelNew;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;
import cn.ffcs.uom.common.vo.PageInfo;
import lombok.Getter;
import lombok.Setter;

/**
 * 外包人员薪酬明细清单
 * 
 * @Title:
 * @Description:
 * @author Wang Yiren
 * @版权 FFCS（C） 2017
 * @date 2018年9月29日
 */
@Controller
@Scope("prototype")
public class OutStaffSalaryDetailListboxExt extends Div implements IdSpace {

    private static final long serialVersionUID = 7719349278474090491L;

    private static final String OUTSTAFF_SALARYDETAIL_LIST_ZUL = "/pages_nmg/staffAndOutStaff/comp/outStaffSalaryDetail_listox_ext.zul";

    private OutStaffSalaryDetailListboxExtBean bean = new OutStaffSalaryDetailListboxExtBean();

    /**
     * 外包人员薪资明细清单：外包人员费用子表 与 外包人员费用主表 想关联
     */
    private OutStaffSalaryDetail outStaffSalaryDetail = new OutStaffSalaryDetail();

    private OutStaffImportListManager outStaffImportListManager = (OutStaffImportListManager) ApplicationContextUtil
            .getBean("outStaffImportListManager");

    /**
     * 下载数据
     */
    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

    @Getter
    @Setter
    private IPortletInfoProvider portletInfoProvider;

    public OutStaffSalaryDetailListboxExt() {
        Executions.createComponents(OUTSTAFF_SALARYDETAIL_LIST_ZUL, this, null);
        Components.wireVariables(this, bean);
        Components.addForwards(this, this, '$');
        this.addForward("onOrgTreeOutStaffQuery", this, "onOrgTreeOutStaffQueryResponse");
    }

    /**
     * 界面初始化
     */
    public void onCreate() {
        /**
         * 绑定年月
         */
        List<NodeVo> yearList = new ArrayList<NodeVo>();
        String[][] year = { { "2012", "2012" }, { "2013", "2013" }, { "2014", "2014" }, { "2015", "2015" },
                { "2016", "2016" }, { "2017", "2017" }, { "2018", "2018" }, { "2019", "2019" }, { "2020", "2020" } };
        for (int i = 0; i < year.length; i++) {
            NodeVo nodeVo = new NodeVo();
            for (int j = 0; j < 1; j++) {
                nodeVo.setId(year[i][j]);
                nodeVo.setName(year[i][j + 1]);
            }
            yearList.add(nodeVo);
        }
        ListboxUtils.rendererForEdit(bean.getYear(), yearList);
        /**
         * 期间
         */
        List<NodeVo> periodList = new ArrayList<NodeVo>();
        String[][] period = { { "01", "01" }, { "02", "02" }, { "03", "03" }, { "04", "04" }, { "05", "05" },
                { "06", "06" }, { "07", "07" }, { "08", "08" }, { "09", "09" }, { "10", "10" }, { "11", "11" },
                { "12", "12" } };
        for (int i = 0; i < period.length; i++) {
            NodeVo nodeVo = new NodeVo();
            for (int j = 0; j < 1; j++) {
                nodeVo.setId(period[i][j]);
                nodeVo.setName(period[i][j + 1]);
            }
            periodList.add(nodeVo);
        }
        ListboxUtils.rendererForEdit(bean.getPeriod(), periodList);
    }

    /**
     * 监听组织树抛出的事件
     * 
     * @param event
     */
    public void onOrgTreeOutStaffQueryResponse(final ForwardEvent event) {
        outStaffSalaryDetail = (OutStaffSalaryDetail) event.getOrigin().getData();
        if (null != outStaffSalaryDetail) {
            this.bean.getStaffCode().setValue(null);
            this.bean.getStaffName().setValue(null);
        }
        // 执行查询
        onQuery();
    }

    /**
     * 查询按钮
     */
    public void onQuery() {
        if (!StrUtil.isEmpty(this.bean.getStaffCode().getValue())) {
            outStaffSalaryDetail.setPsnCode(this.bean.getStaffCode().getValue());
        }
        if (!StrUtil.isEmpty(this.bean.getStaffName().getValue())) {
            outStaffSalaryDetail.setPsnName(this.bean.getStaffName().getValue());
        }
        onQueryOutStaffSalaryDetail();
    }

    /**
     * 查询外包人员列表信息
     */
    public void onQueryOutStaffSalaryDetail() {
        String year = (String) this.bean.getYear().getSelectedItem().getValue();
        String month = (String) this.bean.getPeriod().getSelectedItem().getValue();
        int activPage = bean.getOutStaffSalaryDetailListboxPaging().getActivePage();
        int pageSize = bean.getOutStaffSalaryDetailListboxPaging().getPageSize();
        PageInfo pageInfo = outStaffImportListManager.queryPageInfoByOutStaffSalaryDetail(outStaffSalaryDetail,
                activPage + 1, pageSize, year, month);
        // 清单数据
        data = outStaffImportListManager.getOutStaffSalaryDetailData(outStaffSalaryDetail, year, month);
        // 总条数
        bean.getTotalSize().setValue(String.valueOf(pageInfo.getTotalCount()));
        ListModel list = new BindingListModelList(pageInfo.getDataList(), true);
        this.bean.getOutStaffSalaryDetailListboxs().setModel(list);
        this.bean.getOutStaffSalaryDetailListboxPaging().setTotalSize(pageInfo.getTotalCount());
    }

    /**
     * 每页显示事件
     */
    public void onPageSizeSelect() {
        if (this.bean.getPageListbox() != null && this.bean.getPageListbox().getSelectedItem().getValue() != null) {
            this.bean.getOutStaffSalaryDetailListboxPaging().setActivePage(0);
            this.bean.getOutStaffSalaryDetailListboxPaging()
                    .setPageSize(Integer.parseInt(this.bean.getPageListbox().getSelectedItem().getValue().toString()));
        }
        this.onQueryOutStaffSalaryDetail();
    }

    /**
     * 翻页
     */
    public void onOutStaffSalaryDetailListboxPaging() {
        onQueryOutStaffSalaryDetail();
    }

    /**
     * 清单下载按钮
     * 
     * @throws Exception
     */
    public void onDownloadlist() throws Exception {
        if (data.size() != 0) {
            // 设置字符集
            String charset = "UTF-8";
            String fileName = "外包人员薪酬明细_" + DateUtil.getYYYYMMDD(new Date());
            HttpServletRequest httpRequest = (HttpServletRequest) Executions.getCurrent().getNativeRequest();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ExportExcelNew.exportExcel("", data, os);
            byte[] content = os.toByteArray();
            String encodedName = null;
            encodedName = URLEncoder.encode(fileName + ".xlsx", charset);
            // 将空格替换为+号
            encodedName = encodedName.replace("%20", "+");
            // 解决ie6 bug 或者是火狐浏览器
            if (encodedName.length() > 150 || Servlets.isGecko(httpRequest) || Servlets.isGecko3(httpRequest)) {
                encodedName = new String(encodedName.getBytes(charset), "ISO8859-1");
            }
            Filedownload.save(content, "application/octet-stream", encodedName);
        } else {
            Messagebox.show("数据为空!");
            return;
        }
    }

    /**
     * 重置按钮
     */
    public void onReset() {
        clearVariable();
        this.bean.getTotalSize().setValue(null);
        this.bean.getStaffName().setValue(null);
        this.bean.getStaffCode().setValue(null);
//        bean.getYear().clearSelection();
//        bean.getPeriod().clearSelection();
        ListboxUtils.clearListbox(this.bean.getOutStaffSalaryDetailListboxs());
        this.bean.getOutStaffSalaryDetailListboxPaging().setTotalSize(1);
        
        outStaffSalaryDetail = new OutStaffSalaryDetail();
    }

    /**
     * 清除变量
     */
    public void clearVariable() {
        outStaffSalaryDetail = null;
        data.clear();
    }
}
